package com.zy.kotlinbaselibrary.rx

import com.zy.kotlinbaselibrary.base.bean.BaseEntity
import io.reactivex.Observable
import io.reactivex.ObservableTransformer
import io.reactivex.functions.Function




object RxResultHelper {

    fun  <T> handle_result(): ObservableTransformer<BaseEntity<T>, Optional<T>> {

            return ObservableTransformer {
                it.flatMap(Function {
                    val code = it.code
                    when(code){
                        200 -> createHttpData(it.transform())
                        202 -> Observable.error(Throwable(it.msg))
                        else -> Observable.empty()
                    }
                })
            }
        }

    private fun <T> createHttpData(t: Optional<T>): Observable<Optional<T>> {

       return Observable.create {  emitter ->
            try {
                emitter.onNext(t)
                emitter.onComplete()
            }catch (e: Exception){
                emitter.onError(e)
            }

       }
    }


}
